package cn.darkfire.CarWeb.Controller;

import cn.darkfire.CarWeb.Service.CarService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/car/delCar.do")
public class DelCarController extends HttpServlet {
    @Autowired
    private CarService carService;

    //在spring中注入可能会失败,重写init方法让spring重新获取注入窗口即可
    @Override
    public void init() throws ServletException {
        super.init();
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,this.getServletContext());
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        JSONObject obj = new JSONObject();
        if(carService.deleteCar(id)>0){
            try {
                obj.putOpt("res","success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            try {
                obj.putOpt("res","fail");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(obj);
    }
}
